package org.hive.testserver.domain.model;

import java.util.Map;
import java.util.SortedMap;

import org.apache.commons.lang.StringUtils;
import org.hive.testserver.domain.model.schedule.ScheduleReason;
import org.hive.testserver.domain.util.Clock;
import org.hive.testserver.domain.util.IdBuilder;

public class ExecuteTest extends BaseWork {

	private Test test;

	public ExecuteTest(Test test, ScheduleReason scheduledReason, Slave slave, Clock clock) {
		super(slave, scheduledReason, clock);
		this.test = test;
	}

	public String getId() {
		return new IdBuilder().withEntity(test).withName(uuid).toId();
	}

	public SortedMap<String,String> runContext() {
		return test.getTestRun().getContext();
	}
	
	public String getTestName() {
		return test.getName();
	}
	
	@Override
	public void finished(Slave slave, String result, Map<String, String> workContext) {
		super.finished(slave, result, workContext);
		
		TestState resultState = calculateTestState(result);
		test.updateFromExecution(resultState, duration());
		//FIXME testRun should be responsible for setting its own duration - we are tied up in knots here...
		if (test.isFinished()) {
			test.getTestRun().setDuration(clock.currentTimeMillis() - test.getTestRun().getStarted());
		}
	}

	private TestState calculateTestState(String result) {
		if (StringUtils.equals(TestState.PASSED.toString(), result)) {
			return TestState.PASSED;
		} else if (StringUtils.equals(TestState.FAILED.toString(), result)) {
			return TestState.FAILED;
		} else {
			return TestState.ABORTED;
		}

	}
}
